package com.sxj.corejava.code12_线程;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 石小俊
 * @date 2025年02月25日
 */
public class Test10_线程单例 {

    public static void main(String[] args) {
        MyThreadLocal<String> local = new MyThreadLocal<>();

        Map<Thread,String> map = new HashMap<>();
        map.put(Thread.currentThread(),"admin");
        local.setLocal(map);
        System.out.println(Thread.currentThread()+"线程:"+local.getLocal().get(Thread.currentThread()));

        map.put(Thread.currentThread(),"alice");
        local.setLocal(map);
        System.out.println(Thread.currentThread()+"线程:"+local.getLocal().get(Thread.currentThread()));

        map.put(Thread.currentThread(),"tom");
        local.setLocal(map);
        System.out.println(Thread.currentThread()+"线程:"+local.getLocal().get(Thread.currentThread()));

        new Thread(){
            @Override
            public void run() {
                map.put(Thread.currentThread(),"admin");
                local.setLocal(map);
                System.out.println(Thread.currentThread()+"线程:"+local.getLocal().get(Thread.currentThread()));
            }
        }.start();


        System.out.println(Thread.currentThread()+"线程:"+local.getLocal().get(Thread.currentThread()));
    }

}
class MyThreadLocal<T>{
    // 实现线程单例,表示同一个线程获取到的对象是相同的
    // 设置一个Map属性,其中key对应的是线程
    // 由于key不能重复,因此,同一个线程中存在多个对象时会覆盖原来的对象
    private Map<Thread,T> local = new HashMap<>();

    public Map<Thread, T> getLocal() {
        return local;
    }

    public void setLocal(Map<Thread, T> local) {
        this.local = local;
    }
}